﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Gosocket.SDK
{    
    public abstract class WebManager
    {
        public static string _default_url_service = "https://api.gosocket.net";
        
        public static string   _proxy = null;
        public static int      _port = 0;
        public static string   _proxy_user = null;
        public static string   _proxy_password = null;

        public Guid _ApplicationId { get; set; }
        
        public string _Secret { get; set; }

        public static string GetUrlService()
        {
            return _default_url_service;
        }

        public HttpClient httpClient;

        public void CreateWebClient()
        {
            if (_proxy != null && _port != 0)
            {
                IWebProxy webProxy = new WebProxy(_proxy, _port);
                webProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

                if (!string.IsNullOrEmpty(_proxy_user))
                {
                    webProxy.Credentials = new NetworkCredential(_proxy_user, _proxy_password);
                }

                var httpHandler = new HttpClientHandler();
                httpHandler.AllowAutoRedirect = false;
                httpHandler.Proxy = webProxy;

                httpClient = new HttpClient(httpHandler);
            }
            else
            {
                httpClient = new HttpClient();
            }

            httpClient.BaseAddress = new Uri(GetUrlService());
            httpClient.DefaultRequestHeaders.Authorization = CreateBasicAuthenticationHeader(_ApplicationId.ToString(), _Secret);
            httpClient.Timeout = new TimeSpan(0, 5, 0);
        }

        private AuthenticationHeaderValue CreateBasicAuthenticationHeader(string Username, string Password)
        {
            return new AuthenticationHeaderValue(
                "Basic",
                System.Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(
                string.Format("{0}:{1}", Username, Password)))
            );
        }
    }
}
